import requests
from bs4 import BeautifulSoup as bs
import re
import json

class SpiderAiqiyi():
    def __init__(self):
        self.cache_url='https://cache.video.iqiyi.com/dash?tvid=4073048000&bid=300&vid=32f8220d20f4ab6dc47339190a5ec087&src=01010031010000000000&vt=0&rs=1&uid=&ori=pcw&ps=1&k_uid=3bpngkjftffpfi6qgqkbe5kw3zovwpfq&pt=0&d=0&s=&lid=0&cf=0&ct=0&authKey=46189785d46e68f969a69714b1ff360c&k_tag=1&dfp=a1aac20966c3064fd18a3281d1e0fb23f3d66e1f3a1f64b10017768308dd2cb7d5&locale=zh_cn&pck=&k_err_retries=0&up=&sr=1&qd_v=5&tm=1716003572458&qdy=u&qds=0&k_ft1=704237197590532&k_ft4=1161221786574868&k_ft5=134217729&k_ft7=4&fr_300=120_120_120_120_120_120&fr_500=120_120_120_120_120_120&fr_600=120_120_120_120_120_120&fr_800=120_120_120_120_120_120&fr_1020=120_120_120_120_120_120&bop=%7B%22version%22%3A%2210.0%22%2C%22dfp%22%3A%22a1aac20966c3064fd18a3281d1e0fb23f3d66e1f3a1f64b10017768308dd2cb7d5%22%2C%22b_ft1%22%3A24%7D&ut=0&vf=b9e20951f2f22f244f15b5fd72aaec06'
        self.headers={'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0'}


    def get_m3u8url_list(self):
        response=requests.get(url=self.cache_url)
        # print(type(response))

        html_data = response.text
        # print(html_data)
        json_data=json.loads(html_data)

        m3u8list=json_data["data"]["program"]["video"][2]["m3u8"]
        print(m3u8list)
        m3u8_list=m3u8list.split("\n")
        print(m3u8_list)
        new_list=[]
        pattern="^http://"
        for i in range(len(m3u8_list)):
            if(m3u8_list[i].startswith('http://')):
                new_list.append(m3u8_list[i])
        print(new_list)
        return new_list

    def download_m3u8(self,url_list):

        for i in range(len(url_list)):
            data=requests.get(url_list[i]).content
            # 请求数据
            with open(f'vedio{i}'+'.ts', mode='wb') as f:
                f.write(data)
                print(f'正在保存数据{i}')







if __name__ == '__main__':
    spider=SpiderAiqiyi()
    list=spider.get_m3u8url_list()
    spider.download_m3u8(list)

